<template>
  <div style="max-width: 1080px; margin: 16px auto;">
    <a-card title="我的简历">
      <a-form :model="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
        <a-form-item label="姓名"><a-input v-model:value="form.name" /></a-form-item>
        <a-form-item label="头衔"><a-input v-model:value="form.title" /></a-form-item>
        <a-form-item label="头像">
          <SmartUpload v-model="form.avatar" file-type="image" :max-count="1" />
        </a-form-item>
        <a-form-item label="邮箱"><a-input v-model:value="form.email" /></a-form-item>
        <a-form-item label="电话"><a-input v-model:value="form.phone" /></a-form-item>
        <a-form-item label="地址"><a-input v-model:value="form.location" /></a-form-item>
        <a-form-item label="GitHub"><a-input v-model:value="form.github" /></a-form-item>
        <a-form-item label="LinkedIn"><a-input v-model:value="form.linkedin" /></a-form-item>
        <a-form-item label="个人网站"><a-input v-model:value="form.website" /></a-form-item>
        <a-form-item label="简介">
          <SafeMarkdownEditor v-model="form.summary" :style="{ height: summaryEditorHeight }" />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-space>
            <a-button type="primary" @click="onSave" :loading="loading">保存</a-button>
            <a-button @click="onReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card title="工作经验" style="margin-top: 16px;">
      <a-button type="dashed" @click="openExp()">新增经验</a-button>
      <a-table :data-source="experiences" :columns="expColumns" row-key="id" style="margin-top: 12px;">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-space>
              <a @click="openExp(record)">编辑</a>
              <a-popconfirm title="确认删除该经验？" @confirm="() => doDelExp(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-card title="技能" style="margin-top: 16px;">
      <a-button type="dashed" @click="openSkill()">新增技能</a-button>
      <a-table :data-source="skills" :columns="skillColumns" row-key="id" style="margin-top: 12px;">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-space>
              <a @click="openSkill(record)">编辑</a>
              <a-popconfirm title="确认删除该技能？" @confirm="() => doDelSkill(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-card title="项目" style="margin-top: 16px;">
      <a-button type="dashed" @click="openProject()">新增项目</a-button>
      <a-table :data-source="projects" :columns="projectColumns" row-key="id" style="margin-top: 12px;">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'highlights'">
            <span>{{ record.highlights ? '已填写' : '-' }}</span>
          </template>
          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a @click="openProject(record)">编辑</a>
              <a-popconfirm title="确认删除该项目？" @confirm="() => doDelProject(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-card title="引用的资源" style="margin-top: 16px;">
      <div class="ref">
        <div class="ref-item" v-if="form.avatar">
          <div class="title">头像</div>
          <a-image :src="form.avatar" :width="120" />
          <div class="url">{{ form.avatar }}</div>
        </div>
        <a-divider />
        <div class="title">项目截图 ({{ projectImages.length }})</div>
        <div v-if="!projectImages.length" class="muted">暂无</div>
        <div class="img-grid" v-else>
          <div v-for="u in projectImages" :key="u" class="img-item">
            <a-image :src="u" :width="80" />
            <div class="url ellipsis" :title="u">{{ u }}</div>
          </div>
        </div>
        <a-divider />
        <div class="title">亮点内图片 ({{ highlightImages.length }})</div>
        <div v-if="!highlightImages.length" class="muted">暂无</div>
        <div class="img-grid" v-else>
          <div v-for="u in highlightImages" :key="u" class="img-item">
            <a-image :src="u" :width="80" />
            <div class="url ellipsis" :title="u">{{ u }}</div>
          </div>
        </div>
        <div style="margin-top:8px"><router-link :to="{ name: 'AdminOss' }">前往 OSS 管理</router-link></div>
      </div>
    </a-card>

    <!-- 经验弹窗 -->
    <a-modal v-model:open="expOpen" title="工作经验" @ok="saveExp" :confirm-loading="modalLoading">
      <a-form :model="expForm" layout="vertical">
        <a-form-item label="公司"><a-input v-model:value="expForm.company" /></a-form-item>
        <a-form-item label="职位"><a-input v-model:value="expForm.position" /></a-form-item>
        <a-form-item label="开始日期"><a-date-picker v-model:value="expForm.startDate" value-format="YYYY-MM-DD" /></a-form-item>
        <a-form-item label="结束日期"><a-date-picker v-model:value="expForm.endDate" value-format="YYYY-MM-DD" /></a-form-item>
        <a-form-item label="当前在职"><a-switch v-model:checked="expForm.current" :checked-value="1" :un-checked-value="0" /></a-form-item>
        <a-form-item label="描述"><SafeMarkdownEditor v-model="expForm.description" :style="{ height: expDescEditorHeight }" /></a-form-item>
        <a-form-item label="成就"><SafeMarkdownEditor v-model="expForm.achievements" :style="{ height: expAchvEditorHeight }" /></a-form-item>
        <a-form-item label="排序"><a-input-number v-model:value="expForm.sortOrder" :min="0" /></a-form-item>
      </a-form>
    </a-modal>

    <!-- 技能弹窗 -->
    <a-modal v-model:open="skillOpen" title="技能" @ok="saveSkill" :confirm-loading="modalLoading">
      <a-form :model="skillForm" layout="vertical">
        <a-form-item label="名称"><a-input v-model:value="skillForm.name" /></a-form-item>
        <a-form-item label="分类"><a-input v-model:value="skillForm.category" /></a-form-item>
        <a-form-item label="等级(1-5)"><a-input-number v-model:value="skillForm.level" :min="1" :max="5" /></a-form-item>
        <a-form-item label="描述"><SafeMarkdownEditor v-model="skillForm.description" :style="{ height: skillDescEditorHeight }" /></a-form-item>
        <a-form-item label="排序"><a-input-number v-model:value="skillForm.sortOrder" :min="0" /></a-form-item>
      </a-form>
    </a-modal>

    <!-- 项目弹窗 -->
    <a-modal v-model:open="projectOpen" title="项目" @ok="saveProject" :confirm-loading="modalLoading" width="900px">
      <a-form :model="projectForm" layout="vertical">
        <a-form-item label="名称"><a-input v-model:value="projectForm.name" /></a-form-item>
        <a-form-item label="技术栈"><a-input v-model:value="projectForm.technologies" /></a-form-item>
        <a-form-item label="项目描述"><SafeMarkdownEditor v-model="projectForm.description" :style="{ height: projDescEditorHeight }" /></a-form-item>
        <a-form-item label="GitHub"><a-input v-model:value="projectForm.githubUrl" /></a-form-item>
        <a-form-item label="演示链接"><a-input v-model:value="projectForm.demoUrl" /></a-form-item>
        <a-form-item label="截图">
          <SmartUpload v-model="projectForm.imageUrl" file-type="image" :max-count="1" />
        </a-form-item>
        <a-form-item label="开始日期"><a-date-picker v-model:value="projectForm.startDate" value-format="YYYY-MM-DD" /></a-form-item>
        <a-form-item label="结束日期"><a-date-picker v-model:value="projectForm.endDate" value-format="YYYY-MM-DD" /></a-form-item>
        <a-form-item label="项目职责/项目亮点">
          <SafeMarkdownEditor v-model="projectForm.highlights" :style="{ height: highlightsEditorHeight }" />
        </a-form-item>
        <a-form-item label="排序"><a-input-number v-model:value="projectForm.sortOrder" :min="0" /></a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { ResumeDetailVO, WorkExperienceVO, SkillVO, ProjectVO } from '@/types/api'
import { getMyResume, upsertMyResume, addExperience, updateExperience, deleteExperience, addSkill, updateSkill, deleteSkill, addProject, updateProject, deleteProject } from '@/api/resume'
import { extractImageUrls } from '@/utils/content'
import SmartUpload from '@/components/SmartUpload.vue'
import SafeMarkdownEditor from '@/components/SafeMarkdownEditor.vue'

const loading = ref(false)
const form = reactive<Partial<ResumeDetailVO>>({})
const experiences = ref<WorkExperienceVO[]>([])
const skills = ref<SkillVO[]>([])
const projects = ref<ProjectVO[]>([])
const summaryEditorHeight = 'min(40vh, 300px)'
const expDescEditorHeight = 'min(40vh, 300px)'
const expAchvEditorHeight = 'min(40vh, 300px)'
const skillDescEditorHeight = 'min(40vh, 260px)'
const projDescEditorHeight = 'min(40vh, 300px)'
const highlightsEditorHeight = 'min(50vh, 420px)'

async function load() {
  loading.value = true
  try {
    const resp = await getMyResume()
    if (resp.code === 0) {
      Object.assign(form, resp.data || {})
      experiences.value = (resp.data?.experiences || []) as any
      skills.value = (resp.data?.skills || []) as any
      projects.value = (resp.data?.projects || []) as any
    }
  } finally {
    loading.value = false
  }
}

async function onSave() {
  loading.value = true
  try {
    const resp = await upsertMyResume(form)
    if (resp.code === 0) {
      message.success('保存成功')
      load()
    }
  } finally {
    loading.value = false
  }
}

function onReset() {
  load()
}

const expOpen = ref(false)
const skillOpen = ref(false)
const projectOpen = ref(false)
const modalLoading = ref(false)

const expForm = reactive<Partial<WorkExperienceVO>>({ current: 0, sortOrder: 0 })
const skillForm = reactive<Partial<SkillVO>>({ level: 3, sortOrder: 0 })
const projectForm = reactive<Partial<ProjectVO>>({ sortOrder: 0, highlights: '', name: '' })

function openExp(row?: any) {
  Object.assign(expForm, row || { current: 0, sortOrder: 0 })
  ;(expForm as any).id = row?.id
  expOpen.value = true
}
function openSkill(row?: any) {
  Object.assign(skillForm, row || { level: 3, sortOrder: 0 })
  ;(skillForm as any).id = row?.id
  skillOpen.value = true
}
function openProject(row?: any) {
  Object.assign(projectForm, { sortOrder: 0, highlights: '', name: '', technologies: '', githubUrl: '', demoUrl: '', imageUrl: '', startDate: '', endDate: '' })
  if (row) Object.assign(projectForm, row)
  ;(projectForm as any).id = row?.id
  projectOpen.value = true
}

async function saveExp() {
  modalLoading.value = true
  try {
    if ((expForm as any).id) {
      const resp = await updateExperience((expForm as any).id, expForm as any)
      if (resp.code === 0) message.success('已更新')
    } else {
      const resp = await addExperience(expForm as any)
      if (resp.code === 0) message.success('已新增')
    }
    expOpen.value = false
    load()
  } finally { modalLoading.value = false }
}
async function saveSkill() {
  modalLoading.value = true
  try {
    if ((skillForm as any).id) {
      const resp = await updateSkill((skillForm as any).id, skillForm as any)
      if (resp.code === 0) message.success('已更新')
    } else {
      const resp = await addSkill(skillForm as any)
      if (resp.code === 0) message.success('已新增')
    }
    skillOpen.value = false
    load()
  } finally { modalLoading.value = false }
}
async function saveProject() {
  modalLoading.value = true
  try {
    if (!projectForm.name || !projectForm.name.trim()) {
      message.warning('请输入项目名称')
      return
    }
    if ((projectForm as any).id) {
      const resp = await updateProject((projectForm as any).id, projectForm as any)
      if (resp.code === 0) message.success('已更新')
    } else {
      const resp = await addProject(projectForm as any)
      if (resp.code === 0) message.success('已新增')
    }
    projectOpen.value = false
    load()
  } finally { modalLoading.value = false }
}

const expColumns = computed(() => [
  { title: '公司', dataIndex: 'company' },
  { title: '职位', dataIndex: 'position' },
  { title: '开始', dataIndex: 'startDate' },
  { title: '结束', dataIndex: 'endDate' },
  { title: '在职', dataIndex: 'current' },
  { title: '排序', dataIndex: 'sortOrder' },
  { title: '操作', key: 'actions' }
])

const skillColumns = computed(() => [
  { title: '名称', dataIndex: 'name' },
  { title: '分类', dataIndex: 'category' },
  { title: '等级', dataIndex: 'level' },
  { title: '排序', dataIndex: 'sortOrder' },
  { title: '操作', key: 'actions' }
])

const projectColumns = computed(() => [
  { title: '名称', dataIndex: 'name' },
  { title: '技术栈', dataIndex: 'technologies' },
  { title: '开始', dataIndex: 'startDate' },
  { title: '结束', dataIndex: 'endDate' },
  { title: '亮点', dataIndex: 'highlights' },
  { title: '排序', dataIndex: 'sortOrder' },
  { title: '操作', key: 'actions' }
])

async function doDelExp(id: number) {
  const resp = await deleteExperience(id)
  if (resp.code === 0) { message.success('已删除'); load() }
}
async function doDelSkill(id: number) {
  const resp = await deleteSkill(id)
  if (resp.code === 0) { message.success('已删除'); load() }
}
async function doDelProject(id: number) {
  const resp = await deleteProject(id)
  if (resp.code === 0) { message.success('已删除'); load() }
}

const projectImages = computed(() => (projects.value || []).map(p => p.imageUrl).filter(Boolean) as string[])
const highlightImages = computed(() => {
  const arr: string[] = []
  for (const p of (projects.value || [])) {
    if (p.highlights) arr.push(...extractImageUrls(p.highlights))
  }
  return Array.from(new Set(arr))
})

onMounted(load)
</script>

<style scoped>
.ref { display: grid; gap: 8px; }
.ref .title { font-weight: 600; }
.ref .muted { color: rgba(0,0,0,0.45); }
.img-grid { display: grid; gap: 8px; }
.img-item { display: grid; grid-template-columns: 80px 1fr; gap: 6px; align-items: center; }
.url { font-size: 12px; color: rgba(0,0,0,0.6); word-break: break-all; }
.ellipsis { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
</style>
